<?php

/*
 *
 */

class DB_Mysql extends DB {

	public function getType() {
		return 'mysql';
	}

	protected function _query($query) {
		if ($this->debug) {
			static $queries = array();

			$time = microtime(true);
		}

		$this->lastQuery = $query;

		$result = mysql_query($query, $this->conn);

		if ($this->debug) {
			$diff = microtime(true) - $time;
			$queries[] = array($query, $diff);
		}

		if (!mysql_errno()) {
			return $result;
		}else{
			trigger_error(mysql_error($this->conn) . "\n query: $query");
			return false;
		}
	}

	protected function _connect($server, $user, $pswd, $db) {

		$this->conn = @mysql_connect($server, $user, $pswd, TRUE, 2);

		if (!$this->conn || !mysql_select_db($db)) {
			$this->_errorPage("DB connect Error: " . mysql_error());
		}

		if ($this->collat) {
			mysql_query("SET NAMES " . $this->charset . ' COLLATE ' . $this->collat);
		} else {
			mysql_query("SET NAMES " . $this->charset);
		}

		return $this->conn;
	}

	protected function _closeConnect() {
		return mysql_close($this->conn);
	}

	protected function _escape_string($str) {
		return mysql_real_escape_string($str);
	}

	protected function _encode_blob($data) {
		return "'" . mysql_real_escape_string($data, $this->conn);
	}

	public function lockTable($table){

	}

	public function unlockTables(){
		$this->_query("UNLOCK TABLES");
	}

	public function tableExists($table){

	}

	public function insertId() {
		return mysql_query('SELECT LAST_INSERT_ID()');
	}

	public function affectedRows() {
		return mysql_affected_rows($this->conn);
	}

	public function result($result = null){
		if($result === null){
			$result = $this->result;
		}

		if ($result && mysql_num_rows($result) > 0) {
			$array = mysql_fetch_row($result);
			return $array[0];
		}
		return FALSE;
	}

	public function resultArray($result = null){
		if($result === null){
			$result = $this->result;
		}

		if($result){
			$arr = array();
			while($r = mysql_fetch_array($result)){
				$arr[] = $r;
			}
			 
			if(count($arr) == 1){
				return $arr[0];
			}
			 
			return $arr;
		}

		return NULL;
	}

	public function resultObject($result = null){
		if($result === null){
			$result = $this->result;
		}

		if($result){
			$arr = array();
			while($r = mysql_fetch_object($result)){
				$arr[] = $r;
			}
			 
			if(count($arr) == 1){
				return $arr[0];
			}
			 
			return $arr;
		}

		return NULL;
	}

	public function fetchArray($result){
		if ($result) {
			return mysql_fetch_array($result, MYSQL_ASSOC);
		}
	}

	public function fetchObject($result){
		if ($result) {
			return mysql_fetch_object($result);
		}
	}
}